<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>线程池监控中心</title>
    <!-- 引入Vue -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.5.21/vue.global.prod.min.js"></script>
    <!-- 引入Element Plus -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/element-plus/2.11.1/index.full.min.js"></script>

    <!-- 引入Axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
            padding: 20px;
        }
        .chart-container {
            width: 100%;
            height: 400px;
        }
        .el-table .warning-row {
            background: oldlace;
        }
        .el-table .danger-row {
            background: #fff1f0;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 16px;
            margin-bottom: 20px;
        }
        .stat-card {
            padding: 16px;
            border-radius: 6px;
            background-color: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stat-card .value {
            font-size: 24px;
            font-weight: bold;
            margin: 8px 0;
        }
        .stat-card .label {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div id="app" class="container">
    <div class="header">
        <h1>线程池监控中心</h1>
        <el-button type="primary" @click="collectStats">
            <el-icon><Refresh /></el-icon>
            收集统计信息
        </el-button>
    </div>

    <!-- 总体统计卡片 -->
    <div class="card">
        <h2>总体统计</h2>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="label">线程池总数</div>
                <div class="value">{{ totalPools }}</div>
            </div>
            <div class="stat-card">
                <div class="label">总活跃线程数</div>
                <div class="value">{{ totalActiveThreads }}</div>
            </div>
            <div class="stat-card">
                <div class="label">总任务数</div>
                <div class="value">{{ totalTaskCount }}</div>
            </div>
            <div class="stat-card">
                <div class="label">总完成任务数</div>
                <div class="value">{{ totalCompletedTaskCount }}</div>
            </div>
            <div class="stat-card">
                <div class="label">总拒绝任务数</div>
                <div class="value" :class="{ 'text-danger': totalRejectedCount > 0 }">{{ totalRejectedCount }}</div>
            </div>
        </div>
    </div>

    <!-- 线程池统计表格 -->
    <div class="card">
        <h2>线程池当前状态</h2>
        <el-table
                :data="threadPoolStats"
                border
                style="width: 100%"
                :row-class-name="tableRowClassName">
            <el-table-column prop="poolName" label="线程池名称" width="180"></el-table-column>
            <el-table-column prop="activeThreads" label="活跃线程数"></el-table-column>
            <el-table-column prop="corePoolSize" label="核心线程数"></el-table-column>
            <el-table-column prop="maximumPoolSize" label="最大线程数"></el-table-column>
            <el-table-column prop="poolSize" label="当前线程数"></el-table-column>
            <el-table-column prop="queueSize" label="队列任务数"></el-table-column>
            <el-table-column prop="queueCapacity" label="队列容量"></el-table-column>
            <el-table-column prop="activeThreadRatio" label="活跃线程比例">
                <template #default="scope">
                    {{ (scope.row.activeThreadRatio * 100).toFixed(2) }}%
                </template>
            </el-table-column>
            <el-table-column prop="queueUsageRatio" label="队列使用率">
                <template #default="scope">
                    {{ (scope.row.queueUsageRatio * 100).toFixed(2) }}%
                </template>
            </el-table-column>
            <el-table-column prop="rejectedCount" label="拒绝任务数"></el-table-column>
        </el-table>
    </div>

    <!-- 趋势分析图表 -->
    <div class="card">
        <h2>线程池趋势分析</h2>
        <el-select
                v-model="selectedPool"
                placeholder="选择线程池"
                style="margin-bottom: 16px;">
            <el-option
                    v-for="pool in threadPoolStats"
                    :key="pool.poolName"
                    :label="pool.poolName"
                    :value="pool.poolName">
            </el-option>
        </el-select>

        <div v-if="selectedPool" class="chart-container" ref="chartContainer"></div>
        <div v-else class="chart-container" style="display: flex; align-items: center; justify-content: center; color: #999;">
            请选择一个线程池查看趋势图表
        </div>
    </div>

    <!-- 趋势数据表格 -->
    <div class="card">
        <h2>线程池趋势统计</h2>
        <el-table
                :data="threadPoolTrends"
                border
                style="width: 100%">
            <el-table-column prop="poolName" label="线程池名称" width="180"></el-table-column>
            <el-table-column prop="avgActiveThreadRatio" label="平均活跃线程比例">
                <template #default="scope">
                    {{ (scope.row.avgActiveThreadRatio * 100).toFixed(2) }}%
                </template>
            </el-table-column>
            <el-table-column prop="avgQueueUsageRatio" label="平均队列使用率">
                <template #default="scope">
                    {{ (scope.row.avgQueueUsageRatio * 100).toFixed(2) }}%
                </template>
            </el-table-column>
            <el-table-column prop="totalRejectedCount" label="总拒绝任务数"></el-table-column>
            <el-table-column prop="taskCompletionRatio" label="任务完成率">
                <template #default="scope">
                    {{ (scope.row.taskCompletionRatio * 100).toFixed(2) }}%
                </template>
            </el-table-column>
        </el-table>
    </div>
</div>

<script>
    const { createApp, ref, onMounted, computed, watch } = Vue;
    const { ElButton, ElTable, ElTableColumn, ElSelect, ElOption, ElIcon } = ElementPlus;
   // const { Refresh } = ElementPlusIconsVue;

    createApp({
        components: {
            ElButton,
            ElTable,
            ElTableColumn,
            ElSelect,
            ElOption,
            ElIcon,
            //Refresh
        },
        setup() {
            // 数据
            const threadPoolStats = ref([]);
            const threadPoolTrends = ref([]);
            const selectedPool = ref('');
            const chartInstance = ref(null);

            // 计算属性 - 总体统计
            const totalPools = computed(() => threadPoolStats.value.length);
            const totalActiveThreads = computed(() => {
                return threadPoolStats.value.reduce((sum, stat) => sum + stat.activeThreads, 0);
            });
            const totalTaskCount = computed(() => {
                return threadPoolStats.value.reduce((sum, stat) => sum + stat.taskCount, 0);
            });
            const totalCompletedTaskCount = computed(() => {
                return threadPoolStats.value.reduce((sum, stat) => sum + stat.completedTaskCount, 0);
            });
            const totalRejectedCount = computed(() => {
                return threadPoolStats.value.reduce((sum, stat) => sum + stat.rejectedCount, 0);
            });

            // 初始化图表
            const initChart = () => {
                if (chartInstance.value) {
                    chartInstance.value.dispose();
                }
                const container = document.querySelector('.chart-container');
                chartInstance.value = echarts.init(container);
            };

            // 更新图表数据
            const updateChart = () => {
                if (!selectedPool.value || !chartInstance.value) return;

                // 找到选中的线程池趋势数据
                const trend = threadPoolTrends.value.find(t => t.poolName === selectedPool.value);
                if (!trend) return;

                // 模拟时间序列数据（实际应用中应该从后端获取历史数据）
                const hours = Array.from({length: 24}, (_, i) => `${i}:00`);
                const activeThreadRatios = Array.from({length: 24}, () =>
                    Math.max(0, Math.min(1, trend.avgActiveThreadRatio + (Math.random() - 0.5) * 0.3))
                );
                const queueUsageRatios = Array.from({length: 24}, () =>
                    Math.max(0, Math.min(1, trend.avgQueueUsageRatio + (Math.random() - 0.5) * 0.2))
                );

                const option = {
                    title: {
                        text: `${selectedPool.value} 线程池趋势`,
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross'
                        }
                    },
                    legend: {
                        data: ['活跃线程比例', '队列使用率'],
                        top: 30
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: hours
                    },
                    yAxis: {
                        type: 'value',
                        max: 1,
                        axisLabel: {
                            formatter: '{value}%'
                        },
                        splitArea: {
                            show: true
                        }
                    },
                    series: [
                        {
                            name: '活跃线程比例',
                            type: 'line',
                            smooth: true,
                            data: activeThreadRatios.map(v => v * 100),
                            lineStyle: {
                                width: 3
                            },
                            areaStyle: {}
                        },
                        {
                            name: '队列使用率',
                            type: 'line',
                            smooth: true,
                            data: queueUsageRatios.map(v => v * 100),
                            lineStyle: {
                                width: 3
                            },
                            areaStyle: {}
                        }
                    ]
                };

                chartInstance.value.setOption(option);
            };

            // 加载统计数据
            const loadStats = () => {
                let url = window.location.href.replace('/threadpool.html', '/api/thread-pools/stats');
                axios.get(url)
                    .then(response => {
                        threadPoolStats.value = response.data;
                        if (threadPoolStats.value.length > 0 && !selectedPool.value) {
                            selectedPool.value = threadPoolStats.value[0].poolName;
                        }
                    })
                    .catch(error => {
                        console.error('加载统计数据失败:', error);
                        ElMessage.error('加载统计数据失败');
                    });
            };

            // 加载趋势数据
            const loadTrends = () => {
                let url = window.location.href.replace('/threadpool.html', '/api/thread-pools/trend');
                axios.get(url)
                    .then(response => {
                        const trendMap = response.data;
                        threadPoolTrends.value = Object.keys(trendMap).map(key => {
                            return { ...trendMap[key], poolName: key };
                        });
                    })
                    .catch(error => {
                        console.error('加载趋势数据失败:', error);
                        ElMessage.error('加载趋势数据失败');
                    });
            };

            // 收集统计信息
            const collectStats = () => {
                let url = window.location.href.replace('/threadpool.html', '/api/thread-pools/monitor');
                axios.get(url)
                    .then(() => {
                        ElMessage.success('统计信息收集成功');
                        // 收集后重新加载数据
                        loadStats();
                        loadTrends();
                    })
                    .catch(error => {
                        console.error('收集统计信息失败:', error);
                        ElMessage.error('收集统计信息失败');
                    });
            };

            // 表格行样式
            const tableRowClassName = ({ row }) => {
                if (row.activeThreadRatio > 0.8) {
                    return 'warning-row';
                }
                if (row.rejectedCount > 0) {
                    return 'danger-row';
                }
                return '';
            };

            // 初始化
            onMounted(() => {
                initChart();
                loadStats();
                loadTrends();

                // 监听窗口大小变化，重绘图表
                window.addEventListener('resize', () => {
                    if (chartInstance.value) {
                        chartInstance.value.resize();
                    }
                });
            });

            // 监听选中的线程池变化，更新图表
            watch(selectedPool, () => {
                updateChart();
            });

            // 监听趋势数据变化，更新图表
            watch(threadPoolTrends, () => {
                updateChart();
            });

            return {
                threadPoolStats,
                threadPoolTrends,
                selectedPool,
                totalPools,
                totalActiveThreads,
                totalTaskCount,
                totalCompletedTaskCount,
                totalRejectedCount,
                collectStats,
                tableRowClassName
            };
        }
    }).use(ElementPlus).mount('#app');
</script>
</body>
</html>
